package com.wyq.new_springboot.config;

import com.wyq.new_springboot.util.result.Result;
import com.wyq.new_springboot.util.result.ResultCode;
import com.wyq.new_springboot.util.result.ResultGenerator;
import org.apache.shiro.authz.UnauthenticatedException;
import org.apache.shiro.authz.UnauthorizedException;
import org.springframework.ui.Model;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * controller增强器
 * @Author weiyaqiang
 * @create 2021/4/7 11:27
 */
@ControllerAdvice
public class MyControllerAdvice {


    /**
     * 应用到所有@RequestMapping注解方法，在其执行之前初始化数据绑定器
     * @param binder
     */
    @InitBinder
    public void initBinder(WebDataBinder binder) {}

    /**
     * 把值绑定到Model中，使全局@RequestMapping可以获取到该值
     * @param model
     */
    @ModelAttribute
    public void addAttributes(Model model) {
        model.addAttribute("author", "weiyaqiang");
    }

    @ResponseBody
    @ExceptionHandler(value = Exception.class)
    public Result errorHandler(Exception e){
       return ResultGenerator.genFailResult(ResultCode.FAIL,e.getMessage());
    }
    /**
     * 拦截捕捉自定义异常 MyException.class
     * @param e
     * @return
     */
    @ResponseBody
    @ExceptionHandler(value = MyException.class)
    public Result myErrorHandler(MyException e) {
        return ResultGenerator.genFailResult(ResultCode.FAIL,e.getMessage());
    }

    @ExceptionHandler(UnauthorizedException.class)
    @ResponseBody
    public Result defaultExceptionHandler(HttpServletResponse response, HttpServletRequest req, Exception e) throws ServletException, IOException {
        String message = e.getMessage();
        if(message.contains("role")){
            //使用重定向
            req.getRequestDispatcher("/test/noAuth").forward(req,response);
            return null;
        }else{
            return ResultGenerator.genFailResult(ResultCode.FAIL,e.getMessage());
        }
    }

    @ExceptionHandler(UnauthenticatedException.class)
    @ResponseBody
    public Result defaultExceptionHandle(HttpServletRequest req, Exception e){
        System.out.println("message===="+e.getMessage());
        return ResultGenerator.genFailResult(ResultCode.FAIL,e.getMessage());
    }




}
